package com.hmdp.utils;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.hmdp.service.impl.ShopServiceImpl.CACHE_REBUILD_EXECUTOR;
@Slf4j
@Component
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,timeUnit);
    }

    //逻辑过期
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        redisData.setData(value);
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));

    }
    //缓存穿透
    public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type , Function<ID,R> dbFallback, Long time, TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1.从redis中查询缓存
        String JSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(JSON)) {
            //2.如果查询结果不为空，那么将数据进行转换然后返回
            return JSONUtil.toBean(JSON, type);
        }
        //如果查询出来的值是""那么说明击中 空字符串，直接返回空值即可
        if (JSON != null) {
            return null;
        }
        //3.如果不存在，那么就从数据库里面查询出数据
        R r = dbFallback.apply(id);
        if (r == null) {
            //4.1店铺不存在，为向redis存入空值
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            //4.2返回错误信息
            return null;
        }
        //5.如果存在，那么就将数据数据缓存到redis里面，返回查询数据
        this.set(key, r, time, timeUnit);
        return r;
    }

    //获取锁
    private Boolean tryLock(String key) {
        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        //不建议直接返回，直接返回可能出现空指针异常
        return BooleanUtil.isTrue(ifAbsent);
    }

    //释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    //互斥锁解决缓存击穿
    public <R,ID> R queryWithMutex(String keyPrefix,Long id,Class<R> type,Function<ID,R> dbFallback, Long time, TimeUnit timeUnit) {
        R r = null;
        String key = keyPrefix + id;
        //1.从redis中查询商铺缓存
        String JSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(JSON)) {
            //2.如果查询结果不为空，那么将数据进行转换然后返回
            return JSONUtil.toBean(JSON,type);
        }
        //3.如果店铺查询出来的值是 ""那么说明击中了 空字符串，直接返回错误信息即可
        if (JSON != null) {
            return null;
        }

        //4.1实现缓存重建
        //4.2获取互斥锁
        String lockKey = "lock:shop:" + id;
        Boolean tryLock = tryLock(lockKey);
        try {
            if (!tryLock) {
                //4.3获取失败，那么就进行休眠；休眠足够的时间之后，进行递归，直到获取数据或者拿到锁
                Thread.sleep(50);
                return queryWithMutex(keyPrefix,id,type,dbFallback,time,timeUnit);
            }

            //5.成功拿到锁，根据id查询数据库
            //再次对redis进行检查，查看缓存是否存在;如果缓存里面有那么就直接返回
            JSON = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(JSON)) {
                //5.1如果缓存里面有数据，那么就直接返回数据；并且释放锁
                 r = JSONUtil.toBean(JSON, type);
                unLock(lockKey);
                return r;
            }
            //6.如果店铺不存在，那么就从数据库里面查询出数据
             r = dbFallback.apply((ID) id);
            if (r == null) {
                //6.1不存在，向redis存入空值
                stringRedisTemplate.opsForValue().set(key, "", time, timeUnit);
                //6.2返回错误信息
                return null;
            }
            //6.3.如果存在，那么就将数据数据缓存到redis里面，返回查询数据；释放锁
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), time, timeUnit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(key);

        }
        return r;
    }

    //逻辑过期解决缓存击穿
    public <R,ID> R queryWithLogicalExpire(String keyPrefix,Long id,Class<R> type,Function<ID,R> dbFallback, Long time, TimeUnit timeUnit){
        String key = keyPrefix+ id;
        //1.获取缓存
        String JSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(JSON)){
            //2.如果字符串为空，那么就返回空值
            return null;
        }
        //3.不为空，先将json反序列化为对象
        RedisData redisData = JSONUtil.toBean(JSON, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //4.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //5.如果不过期，那么直接返回对象
            return r;
        }
        //5.1已过期，缓存重建
        //6.缓存重建
        //6.1获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Boolean islLock = tryLock(lockKey);
        //6.2判断是否获取锁成功
        if (islLock){
            //6.3成功，开启独立线程，缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                   R r1 = dbFallback.apply((ID) id);
                   this.setWithLogicalExpire(key, r1, time, timeUnit);
                }catch (Exception e){
                    throw new RuntimeException();
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        return r;
    }
}
